package com.afs.electronicforensics.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.afs.electronicforensics.activity.R;
import com.afs.electronicforensics.audiocrop.AudioEditView;
import com.afs.electronicforensics.audiocrop.CropUtil;
import com.afs.electronicforensics.audiocrop.TimerUtils;
import com.afs.electronicforensics.audiocrop.ViewUtil;
import com.hhmd.videocrop.VideoCropActivity;

import java.io.File;
import java.io.IOException;

public class AudioCropActivity extends AppCompatActivity {

    private String inputPath;//输入路径
    private String outputPath;//输出路径

    private Context context = this;
    private String TAG = getClass().getSimpleName();
    private AudioEditView audioEditView;
    private ImageView imgBack;
    private ImageView imgPlayStatus;
    private TextView tvNext;
    private TextView tvStartTime;
    private TextView tvEndTime;
    private SeekBar seekBarVoice;

    private MediaPlayer voicePlayer;
    private boolean isRun;
    private int refreshInterval = 20; // 刷新播放指示器的时间间隔
    private Handler handler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            // 更新播放进度
            audioEditView.updateCursor(msg.what);
        }
    };
    private int currentStartTime;// 滑块最左侧对应时间
    private int currentEndTime;// 滑块最右侧对应时间

    private int virtualPosition;// 模拟播放位置
    private int voiceDuration;
    private int screenWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_crop);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            },1);
        }

        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        screenWidth = metrics.widthPixels;

        initView();
        playVoice(inputPath);

    }
    public static Intent createIntent(Context context, String inputPath, String outputPath) {
        Intent intent = new Intent(context, AudioCropActivity.class);
        intent.putExtra("Audio_CROP_INPUT_PATH", inputPath);
        intent.putExtra("Audio_CROP_OUTPUT_PATH", outputPath);
        return intent;
    }

    private void initView() {
        audioEditView = (AudioEditView) findViewById(R.id.audio_edit_view);
        imgBack = (ImageView) findViewById(R.id.img_back);
        tvNext = (TextView) findViewById(R.id.tv_next);
        tvStartTime = (TextView) findViewById(R.id.tv_start_time);
        tvEndTime = (TextView) findViewById(R.id.tv_end_time);
        seekBarVoice = (SeekBar) findViewById(R.id.seek_bar_voice);
        imgPlayStatus = (ImageView) findViewById(R.id.img_play_status);
        imgPlayStatus.setTag("0");

        this.inputPath = this.getIntent().getStringExtra("Audio_CROP_INPUT_PATH");
        this.outputPath = this.getIntent().getStringExtra("Audio_CROP_OUTPUT_PATH");
        if (TextUtils.isEmpty(this.inputPath) || TextUtils.isEmpty(this.outputPath)) {
            Toast.makeText(this, "输入和输出路径必须有效且不为空", Toast.LENGTH_SHORT).show();
            this.setResult(0);
            this.finish();
        }

        imgPlayStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("1".equals(imgPlayStatus.getTag())) {
                    stopPlay();
                } else {
                    startPlayVoice(false);
                }
            }
        });

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println(currentStartTime+"     "+currentEndTime);
                boolean flag = CropUtil.clip(inputPath, outputPath, currentStartTime, currentEndTime);
                if(flag){
                    Toast.makeText(AudioCropActivity.this, "裁剪成功！", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(AudioCropActivity.this, "裁剪失败！", Toast.LENGTH_SHORT).show();
                }
                AudioCropActivity.this.finish();
            }
        });
        audioEditView.setOnScrollListener(new AudioEditView.OnScrollListener() {
            @Override
            public void onScrollThumb(AudioEditView.ScrollInfo info) {
                Log.d(TAG, info.toString());
                currentStartTime = info.getStartTime();
                currentEndTime = info.getEndTime();
                tvStartTime.setText(TimerUtils.intToTime(info.getStartTime() / 1000));
                tvEndTime.setText(TimerUtils.intToTime(info.getEndTime() / 1000));
                int marginLeft = (int) info.getStartPx() - tvStartTime.getWidth() / 2;
                int marginRight = (int) (screenWidth - info.getEndPx() - tvEndTime.getWidth() / 2);
                ViewUtil.setMargins(tvStartTime, marginLeft, 0, 0, 0);
                ViewUtil.setMargins(tvEndTime, 0, 0, marginRight, 0);
                if (info.getIndexPx() == info.getEndPx()) {
                    stopPlay();
                    virtualPosition = info.getStartTime();
                    if (voicePlayer != null) {
                        voicePlayer.seekTo(info.getStartTime());
                    }
                }
            }

            @Override
            public void onScrollCursor(AudioEditView.ScrollInfo info) {
                if (voicePlayer != null) {
                    voicePlayer.seekTo(info.getIndexTime());
                    virtualPosition = info.getIndexTime();
                }
            }
        });

        seekBarVoice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                float v = seekBar.getProgress() * 1.0F / 100;
                if (voicePlayer != null) {
                    voicePlayer.setVolume(v, v);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**
     * 播放录音
     */
    private void playVoice(AssetFileDescriptor descriptor) {
        if (voicePlayer == null) {
            voicePlayer = new MediaPlayer();
            voicePlayer.setVolume(0.5f, 0.5f);
        } else {
            voicePlayer.stop();
            voicePlayer.reset();
        }
        voicePlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            voicePlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
            voicePlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        voicePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
                // 获取录音最大时长并初始化剪辑view
                voiceDuration = mediaPlayer.getDuration();
                audioEditView.setDuration(voiceDuration);
            }
        });
        isRun = true;
        imgPlayStatus.setTag("1");
        imgPlayStatus.setImageResource(R.drawable.icon_audio_edit_pause);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, refreshInterval);
    }

    private void playVoice(String inputPath) {
        if (voicePlayer == null) {
            voicePlayer = new MediaPlayer();
            voicePlayer.setVolume(0.5f, 0.5f);
        } else {
            voicePlayer.stop();
            voicePlayer.reset();
        }
        voicePlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        File file = new File(inputPath);
        try {
            voicePlayer.setDataSource(this, Uri.fromFile(file));
            voicePlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        voicePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
                // 获取录音最大时长并初始化剪辑view
                voiceDuration = mediaPlayer.getDuration();
                audioEditView.setDuration(voiceDuration);
            }
        });
        isRun = true;
        imgPlayStatus.setTag("1");
        imgPlayStatus.setImageResource(R.drawable.icon_audio_edit_pause);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, refreshInterval);
    }

    /**
     * 开始播放录音
     */
    private void startPlayVoice(boolean seek) {
        if (voicePlayer != null) {
            voicePlayer.start();
            if (seek) {
                voicePlayer.seekTo(currentStartTime);
            }
        }
        isRun = true;
        imgPlayStatus.setTag("1");
        imgPlayStatus.setImageResource(R.drawable.icon_audio_edit_pause);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, refreshInterval);
    }

    /**
     * 停止录音播放
     */
    private void stopVoice() {
        isRun = false;
        if (voicePlayer != null) {
            voicePlayer.pause();
        }
    }

    /**
     * 停止播放
     */
    private void stopPlay() {
        stopVoice();
        imgPlayStatus.setTag("0");
        imgPlayStatus.setImageResource(R.drawable.icon_audio_edit_play);
    }

    /**
     * 释放
     */
    private void release() {
        if (voicePlayer != null) {
            voicePlayer.release();
            voicePlayer = null;
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isRun) {
                if (voicePlayer != null) {
                    // voicePlayer.getCurrentPosition();不准确，有时候返回值小于duration,导致滑不到末尾，所以模拟一下播放位置
                    virtualPosition += refreshInterval;
                    handler.sendEmptyMessage(virtualPosition);
                    handler.postDelayed(this, refreshInterval);
                }
            }
        }
    };

    @Override
    public void finish() {
        super.finish();
        stopPlay();
        release();
    }
}
